package com.guardchina.framework.mybatis.datasource;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.guardchina.framework.mybatis.propeties.RoutingDataSourceProperties;
import com.guardchina.framework.util.exception.SystemException;
import lombok.AllArgsConstructor;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：动态数据源生产者
 *
 * @author lwb
 * @date 2019/3/22 8:45
 */
@AllArgsConstructor
public class RoutingDataSourceProvider {

    private RoutingDataSourceProperties routingDataSourceProperties;

    @PostConstruct
    public void init(){
        if(routingDataSourceProperties.getDruid() == null){
            throw new SystemException("未配置druid主数据源");
        }
    }

    DataSource loadMasterDataSource(){
        return createDruidDataSource(routingDataSourceProperties.getDruid());
    }

    Map<String, DataSource> loadSlaveDataSources(){
        Map<String, DataSource> dataSourceMap = new HashMap<>(routingDataSourceProperties.getSlaves().size());
        routingDataSourceProperties.getSlaves().forEach((k, v) -> dataSourceMap.put(k, createDruidDataSource(v)));

        return dataSourceMap;
    }

    private DataSource createDruidDataSource(Map<String, Object> properties){
        try {
            return DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new SystemException("加载数据库数据源失败", e);
        }
    }

}
